import { useAppStore } from '@/store';
import { config, getWsUrl } from '@/utils/config';

class CommunicationService {
  private socket: WebSocket | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = config.ws.reconnectAttempts;
  private reconnectDelay = config.ws.reconnectDelay;
  private deviceId: string = '';
  private token: string = '';

  connect(token: string, deviceId: string) {
    console.log('CommunicationService.connect 被调用:', { 
      token: token?.substring(0, 20) + '...', 
      deviceId,
      deviceIdType: typeof deviceId,
      deviceIdLength: deviceId?.length
    });
    
    if (this.socket?.readyState === WebSocket.OPEN) {
      console.log('WebSocket已连接，跳过重复连接');
      return;
    }

    this.token = token;
    this.deviceId = deviceId;

    const wsUrl = getWsUrl(deviceId, token);
    console.log('准备连接WebSocket URL:', wsUrl);
    this.socket = new WebSocket(wsUrl);

    this.setupEventListeners();
  }

  private setupEventListeners() {
    if (!this.socket) return;

    this.socket.onopen = () => {
      console.log('WebSocket connected');
      const store = useAppStore();
      store.setConnected(true);
      this.reconnectAttempts = 0;
      
      // 发送认证信息
      this.sendMessage({
        type: 'auth',
        data: {
          token: this.token,
          deviceId: this.deviceId
        }
      });
    };

    this.socket.onclose = () => {
      console.log('WebSocket disconnected');
      const store = useAppStore();
      store.setConnected(false);
      this.attemptReconnect();
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket connection error:', error);
      const store = useAppStore();
      store.setConnected(false);
    };

    this.socket.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        this.handleMessage(message);
      } catch (error) {
        console.error('Failed to parse WebSocket message:', error);
      }
    };
  }

  private handleMessage(message: any) {
    console.log('Received WebSocket message:', message);
    
    switch (message.type) {
      case 'connection_established':
        console.log('WebSocket connection established');
        break;
      case 'heartbeat_response':
        console.log('Heartbeat response received');
        break;
      case 'text_received':
        console.log('Text received:', message.data);
        // 这里可以触发通知或更新UI
        break;
      case 'mobile_text_input_success':
        console.log('Mobile text input success:', message.data);
        break;
      case 'error':
        console.error('WebSocket error received:', message.data);
        // 处理错误消息
        this.handleError(message.data);
        break;
      case 'warning':
        console.warn('WebSocket warning received:', message.data);
        break;
      case 'info':
        console.log('WebSocket info received:', message.data);
        break;
      case 'auth_success':
        console.log('Authentication successful:', message.data);
        break;
      default:
        console.log('Unknown message type:', message.type);
    }
  }

  private sendMessage(message: any) {
    if (this.socket?.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    }
  }

  private attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('Max reconnection attempts reached');
      return;
    }

    this.reconnectAttempts++;
    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);

    setTimeout(() => {
      console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
      this.connect(this.token, this.deviceId);
    }, delay);
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
      const store = useAppStore();
      store.setConnected(false);
    }
  }

  // 发送文字到指定设备
  sendTextToDevice(targetDeviceId: string, content: string) {
    this.sendMessage({
      type: 'mobile_text_input',
      data: {
        content: content,
        targetDeviceId: targetDeviceId
      }
    });
  }

  // 发送文字同步数据
  sendTextSync(content: string) {
    this.sendMessage({
      type: 'text_sync',
      data: {
        content: content,
        timestamp: new Date().toISOString()
      }
    });
  }

  // 发送心跳
  sendHeartbeat() {
    this.sendMessage({
      type: 'heartbeat',
      data: {
        timestamp: new Date().toISOString()
      }
    });
  }

  // 获取连接状态
  isConnected(): boolean {
    return this.socket?.readyState === WebSocket.OPEN;
  }

  // 处理错误消息
  private handleError(errorData: any) {
    console.error('Handling WebSocket error:', errorData);
    
    // 根据错误类型进行不同处理
    if (errorData.code) {
      switch (errorData.code) {
        case 'AUTH_FAILED':
          console.error('Authentication failed, attempting to reconnect...');
          // 认证失败，尝试重新连接
          this.reconnectAttempts = 0; // 重置重连次数
          setTimeout(() => {
            this.connect(this.token, this.deviceId);
          }, 1000);
          break;
        case 'DEVICE_NOT_FOUND':
          console.error('Device not found:', errorData.message);
          // 设备未找到，可能需要重新注册
          break;
        case 'INVALID_TOKEN':
          console.error('Invalid token, need to re-authenticate');
          // Token无效，需要重新认证
          break;
        case 'RATE_LIMIT':
          console.error('Rate limit exceeded:', errorData.message);
          // 速率限制，等待一段时间后重试
          break;
        default:
          console.error('Unknown error code:', errorData.code, errorData.message);
      }
    }
    
    // 通知UI层有错误发生
    const store = useAppStore();
    store.setLastError({
      type: 'websocket',
      message: errorData.message || 'WebSocket error',
      timestamp: new Date().toISOString()
    });
  }
}

export const communicationService = new CommunicationService(); 